package com.hexb.smh.entity.param.account;

import com.hexb.core.utils.RegexUtils;
import com.hexb.smh.config.SysConfig;
import com.hexb.smh.entity.Account;
import com.hexb.smh.entity.enums.RoleType;
import com.hexb.smh.utils.SmhConstant;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.mindrot.jbcrypt.BCrypt;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.Random;

import static com.hexb.smh.utils.SmhConstant.AVATAR_SIZE;

/**
 * @author : hexb
 */
@Data
public class AccountParam {

    @ApiModelProperty(value = "姓名(5个汉字)", example = "熊小明")
    @Pattern(regexp = "[\u4e00-\u9fa5a-zA-Z\\d]{1,10}", message = "名字只能1到10位中文/字母/数字")
    @NotNull
    private String name;


    @ApiModelProperty(value = "手机号", example = "13312344321")
    @Pattern(regexp = RegexUtils.MOBILE_CN, message = "需要一个合法的中国地区手机号")
    @NotNull
    private String phoneNo;

    @ApiModelProperty(value = "备注(500字以内)", example = "这是一个自建用户")
    @Size(max = 500, message = "备注信息在500字以内")
    private String remarks;

    private RoleType role;

    @EqualsAndHashCode(callSuper = true)
    @Data
    public static class AccountParamInsert extends AccountParam {

        @ApiModelProperty(example = "xxm1982")
        @NotNull
        @Pattern(regexp = "[a-zA-Z\\d#_@.\\-]{2,20}", message = "用户名只能2-20位[数字/字母/@.#_-]")
        private String loginName;

        private Account toAccount() {
            Account account = new Account();
            account.setEnabled(true);
            account.setPassword(BCrypt.hashpw(SysConfig.DEFAULT_PWD, BCrypt.gensalt(12)));
            account.setName(getName());
            account.setLoginName(getLoginName());
            account.setRole(RoleType.salesman);
            account.setPhoneNo(getPhoneNo());
            account.setRemarks(getRemarks());
            account.setAvatar(SmhConstant.avatars[new Random().nextInt(AVATAR_SIZE)]);
            return account;
        }

        public Account toAdmin() {
            Account account = toAccount();
            account.setRole(getRole() == null ? RoleType.admin : RoleType.salesman_manager);
            return account;
        }

        public Account toSalesman() {
            Account account = toAccount();
            account.setRole(RoleType.salesman);
            return account;
        }
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    public static class AccountParamUpdate extends AccountParam {

        public Account toAccount(Integer id) {
            Account account = new Account();
            account.setName(getName());
            account.setPhoneNo(getPhoneNo());
            account.setId(id);
            account.setRemarks(getRemarks());
            account.setUpdateTime(new Date());
            return account;
        }
    }

}
